package ihm;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferStrategy;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

import metier.cases.Case;
import controleur.Controleur;

public class AffichageMap extends JPanel {
	
	private Controleur cont;
	private Graphics buffer;
	private BufferStrategy strategy;
	private RenderingThread renderingThread = new RenderingThread();
	private long lastTimer = 1;
	private long timer = 1;
	private int fps;
	
	public AffichageMap(Controleur cont) {
		super();
		this.cont = cont;
		IHM ihm=cont.getIHM();
		
		ihm.setIgnoreRepaint(true);
		ihm.createBufferStrategy(2);
		
		strategy=ihm.getBufferStrategy();
		buffer=strategy.getDrawGraphics();
		renderingThread.start();
	}	
	
	public void graphicalRender() {
		
		Image img = null;
		
		//Fond :
		buffer.setColor(Color.white);
		buffer.fillRect(0, 0, cont.getIHM().getWidth(), cont.getIHM().getHeight());
		
		//Affichage de la map :
		Case[][] map = cont.getMapEnCours().getCases();
		for(int i = 0; i < map.length; i++) {
			for(int j = 0; j < map[0].length; j++) {
				img = map[i][j].getImageEnCours();
				buffer.drawImage(img, i*30, j*30, this);
			}
		}
		
		//Affichage du h�ro :
		img = cont.getHero().getImageEnCours();
		buffer.drawImage(img, (int)cont.getHero().getPosX()*30, (int)cont.getHero().getPosY()*30, this);
	
		//Affichage FPS :
		buffer.drawString("FPS : "+fps, 50, 50);
		
		strategy.show();
	
	}
	
	class RenderingThread extends Thread {
	     /**
	      *  Ce thread appelle le rafraichissement de notre fenêtre 
	      *  toutes les 10 milli-secondes
	      */
	      public void run(){
	         while(true){
	            try {
	               graphicalRender();
	               timer = System.currentTimeMillis();
	               fps = (int) (1000/(timer - lastTimer));
	               lastTimer = timer;
	            } catch ( Exception e ) {} 
	         }
	      }
	   }   
	
}
